package com.freely.dao.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.validation.ConstraintViolationException;

import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.alibaba.fastjson.JSONObject;
import com.freely.dao.UserDao;
import com.freely.domain.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao{

	/**
	 * 条件查询单一用户
	 */
	@Override
	public List<User> findByCondition(DetachedCriteria criteria) {
		List<User> list =  (List<User>) this.getHibernateTemplate().findByCriteria(criteria);
		if(list == null || list.size() <= 0) {
			return null;
		}
		return list;
	}

	@Override
	public void test(User user) {
		try {
			this.getHibernateTemplate().save(user);
		}catch(ConstraintViolationException e) {
			System.out.println("exception " + e.getMessage());
		}
	}

	/**
	 * 新增用户
	 */
	@Override
	public void addUser(User user){
		this.getHibernateTemplate().save(user);
	}
/*
	*//**
	 * 更新密码
	 *//*
	@Override
	public int updatePassword(String user_email, String user_password) {
		Session session = this.currentSession();
		Query query = session.createQuery("update user set user_password = ?0 where user_email = ?1")
				.setParameter(0, user_password)
				.setParameter(1, user_email);
						
		int result = query.executeUpdate();
		return result;
	}

	*//**
	 * 更新是否在线
	 *//* 
	@Override
	public int updateOnline(boolean flag,Long user_id) {
		Session session = this.currentSession();
		Query query = session.createQuery("update user set user_online = ?0 where user_id = ?1")
						.setParameter(0, flag)
						.setParameter(1, user_id);
		return query.executeUpdate();
	}*/

	@Override
	public int update(JSONObject modifyObj, JSONObject conditionObj) {
		//配置更新语句
		if(modifyObj == null || modifyObj.size() == 0) {
			return -1;
		}
		StringBuilder sb = new StringBuilder("update User set ");
		Set<String> modifyKey = modifyObj.keySet();
		for(String key : modifyKey) {
			sb.append(key + " = :" + key + " , ");
		}
		sb.delete(sb.length() - 2,sb.length());
		if(conditionObj != null && conditionObj.size() > 0) {
			sb.append("where ");
			Set<String> conditionKey = conditionObj.keySet();
			for(String key : conditionKey) {
				sb.append(key + " = :" + key + " and ");
			}
			sb.delete(sb.length() - 4,sb.length());
			modifyObj.putAll(conditionObj);
		}
		System.out.println("[" + sb.toString() + "]");
		// 添加参数
		Session session = this.currentSession();
		Query query = session.createQuery(sb.toString());
		Set<Entry<String,Object>> set = modifyObj.entrySet();
		Iterator<Entry<String,Object>> iterator = set.iterator();
		while(iterator.hasNext()) {
			Entry<String,Object> entry = iterator.next();
			query.setParameter(entry.getKey(), entry.getValue());
		}
		return query.executeUpdate();
	}

	
}
